package com.itheima.tliasbackend.controller;

import com.itheima.tliasbackend.annotation.SysLog;
import com.itheima.tliasbackend.pojo.Dept;
import com.itheima.tliasbackend.service.DeptService;
import com.itheima.tliasbackend.utils.JwtUtils;
import com.itheima.tliasbackend.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

// 部门管理控制器 重构 /xx
// 拼接  序列化 对象 --> 字符串
@RestController
@RequestMapping("/dept")
public class DeptController {

    @Autowired
    private DeptService deptService;

    @GetMapping
    public Result queryList(HttpServletRequest request) {
        // 验票
        String token = request.getHeader("token");

        // 只要不对就报错
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            return Result.error("非法请求");
        }

        List<Dept> empList = deptService.getList();
        return Result.success(empList);
    }

    @SysLog
    // 删除不生效
    @DeleteMapping("/{id}")
    @Transactional(rollbackFor = Exception.class)
    // 开启事务  事务的传播
    public Result removeById(@PathVariable Integer id) {
        deptService.removeById(id); // 开启事务的
        // 出现错误
        int i = 1 / 0;
        return Result.success();
    }

    @SysLog
    @PostMapping
    public Result addOne(@RequestBody Dept dept) {
        deptService.addOne(dept);
        return Result.success();
    }
}